import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { createStorage } from "@/utils/storage";
import Taro from "@tarojs/taro";
import { login, wxLogin, getInfo } from "@/api/user";

// 定义store的state类型
interface UserState {
  userInfo: UserInfo | null;
  token: string | null;
  login: (username: string, password: string) => Promise<void>;
  wxLogin: (code: string) => Promise<void>;
  getUserInfo: () => Promise<void>;
  logout: () => void;
}

// 创建store
export const useUserStore = create<UserState>()(
  persist<UserState>(
    (set) => ({
      userInfo: null,
      token: null,
      // 登录
      login: async (username: string, password: string) => {
        const res = await login(username, password);
        set({
          token: res.data.token,
          userInfo: res.data.userInfo,
        });
      },

      // 微信登录
      wxLogin: async () => {
        try {
          // 调用微信登录获取code
          const { code } = await Taro.login();
          if (!code) {
            throw new Error("微信登录失败");
          }

          // 使用code请求后端接口
          const res = await wxLogin(code);
          set({
            token: res.data.token,
            userInfo: res.data.userInfo,
          });
        } catch (error) {
          Taro.showToast({
            title: error.message || "微信登录失败",
            icon: "none",
          });
          throw error;
        }
      },

      // 获取用户信息
      getUserInfo: async () => {
        const res = await getInfo();
        set({ userInfo: res.data });
      },

      // 退出登录
      logout: () => {
        set({ userInfo: null, token: null });
      },
    }),
    {
      name: "userInfo",
      storage: createJSONStorage(() => createStorage() as any),
    }
  )
);
